<?php

class Articles_model extends CI_Model{

	function getAllArticles(){
		$this->db->order_by("date", "desc");
		$query = $this->db->get('articles');
		return $query->result();
	}
	
	function getNumberOfArticles(){
		return $this->db->get('articles')->num_rows();
	}
	
	function getNumberOfArticlesInCategory($categoryid){
		return $this->db->get_where('articles', array('categoryID'=>$categoryid))->num_rows();
	}
	
	function getLimitOfArticles($lowend, $highend){
		$this->db->order_by("date", "desc");
		$query = $this->db->get('articles', $lowend, $highend);
		return $query->result();
	}
	
	function getLimitOfArticlesInCategory($categoryid, $lowend, $highend){
		$this->db->order_by("date", "desc");
		$query = $this->db->get_where('articles', array('categoryID'=>$categoryid), $lowend, $highend);
		return $query->result();
	}

	// Returns all articles corresponding to a given categoryID
	function getArticles($id){
		$this->db->order_by("date", "desc");
		$query = $this->db->get_where('articles',array('categoryID' => $id));
		return $query->result();
	}

	// Returns all articles corresponding to a given userID
	function getArticlesByUserID($id){
		$this->db->order_by("date", "desc");
		$query = $this->db->get_where('articles',array('userID' => $id));
		return $query->result();
	}

	// Returns the article corresponding to a certain articleID
	function getArticle($id){
		$query = $this->db->get_where('articles',array('articleID' => $id));
		return $query->row();
	}

	// Returns the author(userID) of a specified article(articleID)
	function getUserIDByArticleID($id){
		$query = $this->db->get_where('articles',array('articleID' => $id));
		return $query->row();
	}

	// Returns all article categories
	function getCategories(){
		$query = $this->db->get('article_categories');
		return $query->result();
	}

	// Returns a categoryID as a string, given the categoryname as input
	function getCategoryID($id){
		$query = $this->db->get_where('article_categories',array('name' => $id));
		return $query->row()->articleCategoryID;
	}

	//Returns the name of category corresponding to a given categoryID
	function getCategoryName($id){
		$query = $this->db->get_where('article_categories',array('articleCategoryID' => $id));
		return $query->row()->name;
	}

	// Return all comments corresponding to a certain articleID
	function getComments($id){
		$this->db->order_by("date", "desc");
		$query = $this->db->get_where('article_comments', array('articleID' => $id));
		return $query->result();
	}

	// Inserts a row in the articlestable
	function insertArticle($data){
		$image_data = $this->uploadImage();
		$data2 = array(
		   	'categoryID' => $data['category'] ,		 
		   	'userID' => $this->user_model->getUserIdFromSession(),
			'title' => $data['title'],
			'text' => $data['text'],
			'imgRaw' => $image_data['raw_name'],
			'imgExt' => $image_data['file_ext']	
		);
		$this->db->insert('articles', $data2);
	}
	
	function updateArticle($articleid, $title, $text, $category){
		$data= array('title'=>$title, 'text'=>$text, 'categoryID'=>$category);
		$this->db->update('articles', $data, "articleID = $articleid");
	}

	// Inserts a row in the article_comments table
	function insertComment($data){
		$data2 = array(
			'articleID' => $data['articleID'],
			'userID' => $data['userID'],
			'text' => $data['text']
		);
		$this->db->insert('article_comments', $data2);
	}

	// ----------	Image section	----------

	var $gallery_path;
	var $gallery_path_url;

	function __construct(){
		parent::__construct();

		$this->gallery_path = realpath(APPPATH . '../userimages'); 	// should be user specific?
		$this->gallery_path_url = base_url().'userimages/';			// should be user specific?
	}

	function uploadImage() {

		// Configuration array for the uploaded image
		$config = array(
			'allowed_types' => 'jpg|jpeg|gif|png',
			'upload_path' => $this->gallery_path,
		);

		$this->load->library('upload', $config);
		$this->upload->do_upload();
		$image_data = $this->upload->data();

		// Configuration array for the thumb-image
		$config = array(
			'source_image' => $image_data['full_path'],
			'new_image' => $this->gallery_path . '/thumbs',
			'create_thumb' => true,
			'maintain_ration' => true,
			'width' => 250,
			'height' => 200
		);

		$this->load->library('image_lib', $config);
		$this->image_lib->resize();

		return $image_data;
	}

	// ----------	end Image section	----------

	function deleteArticle($id){
		$this->db->delete('articles',array('articleID' => $id));
		$this->db->delete('article_comments',array('articleID' => $id));
		$this->db->delete('article_bookmarks',array('articleID' => $id));
	}

	function bookmarkArticle($userid, $articleid){
		$data = array('userID'=>$userid, 'articleID'=>$articleid);
		$this->db->insert('article_bookmarks', $data);
	}

	function unbookmarkArticle($userid, $articleid){
		$data = array('userID'=>$userid, 'articleID'=>$articleid);
		$this->db->delete('article_bookmarks', $data);
	}

	function isBookmarked($userid, $articleid){
		$query = $this->db->get_where('article_bookmarks', array('userID'=>$userid, 'articleID'=>$articleid));
		$row = $query->row();
		if($query->num_rows() > 0){
			if(($row->userID == $userid) && ($row->articleID == $articleid)){
				return TRUE;
			}
		}
		return FALSE;
	}

	function getBookmarkedArticles($userid){
		$query = $this->db->select('articleID')->from('article_bookmarks')->where('userID',$userid)->get();
		$articles = array();
		foreach($query->result() as $article){
			array_push($articles, $article->articleID);
				
		}
		if(count($articles)>0){
			$query = $this->db->select('*')->from('articles')->where_in('articleID', $articles)->get();
			return $query->result();
		}

	}
	
	function subscribe($userid, $authorid){
		if(!$this->isSubscribing($userid, $authorid)){
			$data = array('userID' => $userid, 'authorID'=>$authorid);
			$this->db->insert('subscriptions', $data);
		}	
	}
	
	function unsubscribe($userid, $authorid){
		$data = array('userID' => $userid, 'authorID'=>$authorid);
		$this->db->delete('subscriptions', $data);
	}
	
	function isSubscribing($userid, $authorid){
		$query = $this->db->get_where('subscriptions', array('userID'=>$userid, 'authorID'=>$authorid));
		$row = $query->row();
		if($query->num_rows() > 0){
			if(($row->userID == $userid) && ($row->authorID == $authorid)){
				return TRUE;
			}
		}
		return FALSE;
	}
	
	function getSubscriptions($userid){
		$query = $this->db->get_where('subscriptions', array('userID'=>$userid));
		//var_dump($query->result());
		return $query->result();
	}
	
	function getSubscribersEmails($authorid){
		$query = $this->db->select('userID')->from('subscriptions')->where_in('authorID', $authorid)->get();
		$emails = array();
		foreach($query->result() as $result){
			array_push($emails, $this->user_model->getEmail($result->userID));
		}
		return $emails;
	}
	

	function updateRating($articleID, $rating)
    {                    
        $query = $this->db->query("UPDATE articles SET ratingNo = ratingNo+1, ratingSum = ratingSum+'".$rating."',ratingAvg= ratingSum/ratingNo WHERE '".$articleID."'=articleID;");

        return $query;
    }  
}